<template>
  <van-icon
    :color="isCollected ? '#fe7300' : '#777'"
    :name="isCollected ? 'star' : 'star-o'"
    @click="onCollect"
  />
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article'

import { debounce } from 'loadsh'

export default {
  name: 'CollectArticle',
  model: {
    prop: 'isCollected',
    event: 'update-articleCollect'
  },
  props: {
    isCollected: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  methods: {
    onCollect: debounce(async function() {
      try {
        if (this.isCollected) {
          // 已收藏 取消收藏
          await deleteCollect(this.articleId)
          this.$toast.success('取消收藏成功')
        } else {
          // 未收藏 添加收藏
          await addCollect(this.articleId)
          this.$toast.success('添加收藏成功')
        }

        // 更新视图
        this.$emit('update-articleCollect', !this.isCollected)
      } catch (error) {
        this.$toast.fail('操作失败,请稍后重试!')
      }
    }, 200)
  }
}
</script>

<style lang="less" scoped></style>
